package cn.edu.zafu.bigdata.liuwenyi;

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UDPServer {
    public static void main(String[] args) {
        int port = 227; // 服务端监听的端口
        try (DatagramSocket socket = new DatagramSocket(port)) {
            System.out.println("时钟同步服务已启动，端口：" + port);

            byte[] buffer = new byte[1024];
            while (true) {
                DatagramPacket requestPacket = new DatagramPacket(buffer, buffer.length);
                socket.receive(requestPacket); // 接收客户端请求

                InetAddress clientAddress = requestPacket.getAddress();
                int clientPort = requestPacket.getPort();

                // 获取当前时间并格式化
                String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                byte[] responseBytes = currentTime.getBytes();

                // 发送当前时间到客户端
                DatagramPacket responsePacket = new DatagramPacket(responseBytes, responseBytes.length, clientAddress, clientPort);
                socket.send(responsePacket);

                System.out.println("已响应客户端 " + clientAddress + ":" + clientPort + " 时间：" + currentTime);
            }
        } catch (Exception e) {
            System.err.println("服务端发生错误：" + e.getMessage());
        }
    }
}
